<template>
  <div class="product-list-container">
    <!-- 顶部筛选栏 -->
    <div class="filter-bar">
      <div class="filter-left">
        <div class="filter-item">
          <span class="filter-label">分类：</span>
          <el-select
            v-model="filterParams.category"
            placeholder="全部分类"
            clearable
            @change="handleFilterChange"
          >
            <el-option
              v-for="category in categories"
              :key="category.value"
              :label="category.label"
              :value="category.value"
            />
          </el-select>
        </div>

        <div class="filter-item">
          <span class="filter-label">排序：</span>
          <el-select
            v-model="filterParams.sort"
            placeholder="默认排序"
            @change="handleFilterChange"
          >
            <el-option
              v-for="sort in sortOptions"
              :key="sort.value"
              :label="sort.label"
              :value="sort.value"
            />
          </el-select>
        </div>

        <div class="filter-item">
          <span class="filter-label">价格：</span>
          <el-input-number
            v-model="filterParams.minPrice"
            placeholder="最低价"
            :min="0"
            :max="100000"
            controls-position="right"
            @change="handleFilterChange"
          />
          <span class="price-separator">-</span>
          <el-input-number
            v-model="filterParams.maxPrice"
            placeholder="最高价"
            :min="0"
            :max="100000"
            controls-position="right"
            @change="handleFilterChange"
          />
        </div>
      </div>

      <div class="filter-right">
        <el-input
          v-model="filterParams.keyword"
          placeholder="搜索商品名称..."
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 商品列表 -->
    <div class="product-list">
      <!-- 骨架屏加载 -->
      <div v-if="loading" class="skeleton-grid">
        <div v-for="i in 12" :key="i" class="skeleton-item">
          <el-skeleton animated>
            <template #template>
              <el-skeleton-item variant="image" class="skeleton-image" />
              <div class="skeleton-content">
                <el-skeleton-item variant="h3" class="skeleton-title" />
                <el-skeleton-item variant="text" class="skeleton-text" />
                <el-skeleton-item variant="text" class="skeleton-text short" />
                <el-skeleton-item variant="button" class="skeleton-button" />
              </div>
            </template>
          </el-skeleton>
        </div>
      </div>

      <!-- 空状态 -->
      <el-empty v-else-if="products.length === 0" description="暂无商品" :image-size="200">
        <template #description>
          <p>没有找到符合条件的商品</p>
          <el-button type="primary" @click="resetFilters">重置筛选条件</el-button>
        </template>
      </el-empty>

      <!-- 商品网格 -->
      <div v-else class="product-grid">
        <div
          v-for="product in products"
          :key="product.id"
          class="product-card"
          @click="handleProductClick(product)"
        >
          <div class="product-image-container">
            <img
              :src="product.image"
              :alt="product.name"
              class="product-image"
              @error="handleImageError(product)"
            />
            <div v-if="product.tag" class="product-tag">{{ product.tag }}</div>
            <div v-if="product.is_flash_sale" class="flash-sale-tag">秒杀</div>
            <div v-if="product.stock <= 0" class="sold-out-badge">已售罄</div>
          </div>

          <div class="product-info">
            <h3 class="product-name">{{ product.name }}</h3>

            <div class="price-section">
              <span class="current-price">¥{{ product.price }}</span>
              <span class="original-price">¥{{ product.originalPrice }}</span>
              <span class="discount">{{ product.discount }}折</span>
            </div>

            <div class="sales-info">
              <span class="sales-count">已售{{ product.sold }}件</span>
              <span class="stock-count">剩余{{ product.stock }}件</span>
            </div>

            <div class="progress-bar">
              <el-progress
                :percentage="product.soldPercent"
                :color="progressColors"
                :show-text="false"
              />
            </div>

            <el-button
              class="add-cart-btn"
              :class="{ disabled: product.stock <= 0 }"
              :disabled="product.stock <= 0"
              @click.stop="handleAddToCart(product)"
            >
              <el-icon><ShoppingCart /></el-icon>
              {{ product.stock > 0 ? '加入购物车' : '已售罄' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[12, 24, 48, 96]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, ShoppingCart } from '@element-plus/icons-vue'

const router = useRouter()

interface Product {
  id: number
  name: string
  price: number
  originalPrice: number
  discount: string
  image: string
  stock: number
  sold: number
  soldPercent: number
  tag?: string
  category?: string
  is_flash_sale?: boolean
  flash_sale_price?: number
  flash_sale_stock?: number
  flash_sale_start_time?: string
  flash_sale_end_time?: string
}

interface FilterParams {
  category: string
  sort: string
  minPrice: number | null
  maxPrice: number | null
  keyword: string
}

interface Pagination {
  current: number
  pageSize: number
  total: number
}

// 筛选参数
const filterParams = reactive<FilterParams>({
  category: '',
  sort: 'default',
  minPrice: null,
  maxPrice: null,
  keyword: '',
})

// 分页参数
const pagination = reactive<Pagination>({
  current: 1,
  pageSize: 12,
  total: 0,
})

const loading = ref(false)
const products = ref<Product[]>([])

// 分类选项
const categories = ref([
  { value: 'digital', label: '手机数码' },
  { value: 'computer', label: '电脑办公' },
  { value: 'appliance', label: '家用电器' },
  { value: 'clothing', label: '服装鞋帽' },
  { value: 'food', label: '食品生鲜' },
])

// 排序选项
const sortOptions = ref([
  { value: 'default', label: '默认排序' },
  { value: 'price_asc', label: '价格从低到高' },
  { value: 'price_desc', label: '价格从高到低' },
  { value: 'sales_desc', label: '销量从高到低' },
  { value: 'newest', label: '最新上架' },
])

// 进度条颜色
const progressColors = computed(() => [
  { color: '#f56c6c', percentage: 20 },
  { color: '#e6a23c', percentage: 40 },
  { color: '#5cb87a', percentage: 60 },
  { color: '#1989fa', percentage: 80 },
  { color: '#6f7ad3', percentage: 100 },
])

// 模拟商品数据
const mockProducts: Product[] = [
  {
    id: 1,
    name: 'iPhone 15 Pro 256GB 原色钛金属',
    price: 7999,
    originalPrice: 8999,
    discount: '8.8',
    image:
      'https://img10.360buyimg.com/mobilecms/s360x360_jfs/t1/213439/35/35971/72524/657f6ab2F04e9e6ad/6a9a49b1e9c01a1b.jpg',
    stock: 5,
    sold: 95,
    soldPercent: 95,
    tag: '爆款',
    category: 'digital',
  },
  {
    id: 2,
    name: 'iPhone 15 Pro 256GB 原色钛金属',
    price: 7999,
    originalPrice: 8999,
    discount: '8.8',
    image:
      'https://img10.360buyimg.com/mobilecms/s360x360_jfs/t1/213439/35/35971/72524/657f6ab2F04e9e6ad/6a9a49b1e9c01a1b.jpg',
    stock: 5,
    sold: 95,
    soldPercent: 95,
    tag: '爆款',
    category: 'digital',
  },
  {
    id: 3,
    name: 'iPhone 15 Pro 256GB 原色钛金属',
    price: 7999,
    originalPrice: 8999,
    discount: '8.8',
    image:
      'https://img10.360buyimg.com/mobilecms/s360x360_jfs/t1/213439/35/35971/72524/657f6ab2F04e9e6ad/6a9a49b1e9c01a1b.jpg',
    stock: 5,
    sold: 95,
    soldPercent: 95,
    tag: '爆款',
    category: 'digital',
  },
  // 更多模拟数据... 可以复制您之前的商品数据
]

// 加载商品数据
const loadProducts = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 1000))

    // 这里应该是实际的API调用
    // const response = await api.getProducts({ ...filterParams, ...pagination })

    // 使用模拟数据
    products.value = mockProducts
    pagination.total = mockProducts.length
  } catch (error) {
    ElMessage.error('加载商品失败')
    console.error('加载商品失败:', error)
  } finally {
    loading.value = false
  }
}

// 筛选变化处理
const handleFilterChange = () => {
  pagination.current = 1
  loadProducts()
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  loadProducts()
}

// 重置筛选
const resetFilters = () => {
  Object.assign(filterParams, {
    category: '',
    sort: 'default',
    minPrice: null,
    maxPrice: null,
    keyword: '',
  })
  pagination.current = 1
  loadProducts()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  loadProducts()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.current = page
  loadProducts()
}

// 商品点击
const handleProductClick = (product: Product) => {
  router.push(`/product/detail/${product.id}`)
}

// 加入购物车
const handleAddToCart = async (product: Product) => {
  if (product.stock <= 0) return

  try {
    // 模拟加入购物车API调用
    await new Promise((resolve) => setTimeout(resolve, 500))

    ElMessage.success('已加入购物车')

    // 这里可以触发全局的购物车状态更新
    // useCartStore().addItem(product)
  } catch (error) {
    ElMessage.error('加入购物车失败')
  }
}

// 图片加载失败处理
const handleImageError = (product: Product) => {
  console.error(`图片加载失败: ${product.name}`)
  // 可以设置默认图片
  product.image = 'https://via.placeholder.com/300x300?text=图片加载失败'
}

onMounted(() => {
  loadProducts()
})
</script>

<style scoped lang="scss">
.product-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .filter-left {
    display: flex;
    align-items: center;
    gap: 16px;

    .filter-item {
      display: flex;
      align-items: center;
      gap: 8px;

      .filter-label {
        font-size: 14px;
        color: #606266;
        white-space: nowrap;
      }

      .price-separator {
        margin: 0 8px;
        color: #dcdfe6;
      }

      :deep(.el-input-number) {
        width: 100px;
      }

      /* 自定义选择器样式 */
      :deep(.el-select) {
        .el-input {
          .el-input__wrapper {
            box-shadow: none;
            background: transparent;
            padding: 0;
            cursor: pointer;

            .el-input__inner {
              color: #409eff;
              font-weight: 500;
            }

            .el-input__suffix {
              display: none; /* 隐藏下拉箭头 */
            }
          }

          &.is-focus {
            .el-input__wrapper {
              box-shadow: none !important;
            }
          }
        }
      }
    }
  }

  .filter-right {
    width: 300px;
  }
}

.skeleton-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;

  .skeleton-item {
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    .skeleton-image {
      width: 100%;
      height: 200px;
    }

    .skeleton-content {
      padding: 16px;

      .skeleton-title {
        width: 80%;
        height: 20px;
        margin-bottom: 12px;
      }

      .skeleton-text {
        width: 100%;
        height: 16px;
        margin-bottom: 8px;

        &.short {
          width: 60%;
        }
      }

      .skeleton-button {
        width: 100%;
        height: 36px;
        margin-top: 12px;
      }
    }
  }
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.product-card {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  }

  .product-image-container {
    position: relative;
    width: 100%;
    height: 200px;
    overflow: hidden;

    .product-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.3s ease;
    }

    .product-tag {
      position: absolute;
      top: 10px;
      right: 10px; /* 将普通标签移到右上角 */
      background: linear-gradient(135deg, #667eea, #764ba2);
      color: white;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
      font-weight: bold;
      z-index: 5;
    }

    .flash-sale-tag {
      position: absolute;
      top: 10px;
      left: 10px;
      background: linear-gradient(135deg, #ff4e50, #f9002f);
      color: white;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
      font-weight: bold;
      z-index: 10; /* 确保秒杀标签在最上层 */
      box-shadow: 0 2px 8px rgba(255, 0, 0, 0.3);
    }

    .sold-out-badge {
      position: absolute;
      top: 10px;
      right: 10px;
      background: rgba(0, 0, 0, 0.7);
      color: white;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
    }
  }

  .product-info {
    padding: 16px;

    .product-name {
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 12px;
      line-height: 1.4;
      height: 44px;
      overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

    .price-section {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 8px;

      .current-price {
        font-size: 20px;
        color: #ff4e50;
        font-weight: 700;
      }

      .original-price {
        font-size: 14px;
        color: #999;
        text-decoration: line-through;
      }

      .discount {
        font-size: 12px;
        background: #ff4e50;
        color: white;
        padding: 2px 6px;
        border-radius: 4px;
      }
    }

    .sales-info {
      display: flex;
      justify-content: space-between;
      font-size: 12px;
      color: #666;
      margin-bottom: 8px;
    }

    .progress-bar {
      margin: 12px 0;

      :deep(.el-progress-bar) {
        padding-right: 0;
      }
    }

    .add-cart-btn {
      width: 100%;
      background: linear-gradient(135deg, #ff4e50, #f9d423);
      border: none;
      color: white;
      font-weight: 600;

      &:hover {
        opacity: 0.9;
      }

      &.disabled {
        background: #ccc;
        cursor: not-allowed;

        &:hover {
          opacity: 1;
        }
      }
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 32px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .product-list-container {
    padding: 12px;
  }

  .filter-bar {
    flex-direction: column;
    gap: 16px;

    .filter-left {
      flex-wrap: wrap;
      justify-content: center;
    }

    .filter-right {
      width: 100%;
    }
  }

  .product-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 16px;
  }
}
</style>
